/*
 * FontMetricsDelegate.cpp  0.4.0 / Dec 04, 2010
 *
 * Copyright (c) 2010 - 2011, cute4j.com and contributors.
 *
 * This software is licensed under the LGPL version 2.1 license.
 * A copy of this license is included in the file LICENSE-LGPL.txt.
 */
#include "FontMetricsDelegate.h"

#include "SwingUtilitiesDelegate.h"

// FontMetricsDelegate :: Static Native Calls. ---------------------------------

/*!
 * \brief Fills the specified Font metrics java object.
 *
 * \param env the JNIEnv pointer
 * \param obj the Font metrics java object.
 * \param fontMetrics the Qt font metrics object
 */
void FontMetricsDelegate::getMetrics(JNIEnv *env, jobject obj,
                                     QFontMetrics *fontMetrics)
{
  JNIWrapper::setIntField(env, obj, sm_ascentFID, fontMetrics->ascent());
  JNIWrapper::setIntField(env, obj, sm_descentFID, fontMetrics->descent());
  JNIWrapper::setIntField(env, obj, sm_heightFID, fontMetrics->height());
  JNIWrapper::setIntField(env, obj, sm_leadingFID, fontMetrics->leading());
}

/*!
 * \brief Returns width of the specified string.
 *
 * \param env the JNIEnv pointer
 * \param obj the Font metrics java object.
 * \param fontMetrics the Qt font metrics object
 * \param str the string
 * 
 * \return width of the specified string
 */
jint FontMetricsDelegate::stringWidth(JNIEnv *env, jobject obj,
                                      QFontMetrics *fontMetrics, jstring str)
{
  if (JNISwingWrapper::isSwingThread(env)) {
    return fontMetrics->width(QStringAdapter(env, str));
  }
  return SwingUtilitiesDelegate::
                   invokeIntAndWait(env, obj, sm_stringWidthMID,
                                    reinterpret_cast<jlong>(fontMetrics), str);
}

/*!
 * \brief Initializes FontMetricsDelegate class.
 *
 * \param env the JNIEnv pointer
 * \param cls the Swing font metrics class
 *
 * \exception FatalError if failed
 */
void FontMetricsDelegate::initialize(JNIEnv *env, jclass cls)
{
  Q_ASSERT(env);
  Q_ASSERT(cls);
  Q_ASSERT(!sm_ascentFID);
  if (!INIT_FID(ascent, cls, "I") || !INIT_FID(descent, cls, "I") ||
      !INIT_FID(height, cls, "I") || !INIT_FID(leading, cls, "I") ||
      !INIT_UMID(stringWidth, cls, "(JLjava/lang/String;)I")) {
    FATAL_LOGGED_ERROR("FontMetricsDelegate initialization failed");
  }
}

// FontMetricsDelegate :: Private Static Data Members. -------------------------

jfieldID FontMetricsDelegate::sm_ascentFID = 0;
jfieldID FontMetricsDelegate::sm_descentFID = 0;
jfieldID FontMetricsDelegate::sm_heightFID = 0;
jfieldID FontMetricsDelegate::sm_leadingFID = 0;
jmethodID FontMetricsDelegate::sm_stringWidthMID = 0;
